import Taro ,{ Component } from '@tarojs/taro'
import { View , Text , Image , Canvas , Button , Picker} from '@tarojs/components'

import {
  AtFloatLayout
} from 'taro-ui'

import './exchangeDetail.scss'
import BasePage from "../basePage";

import location_icon from '../../image/ic_location.png'
import {base_url} from "../../network/config";
import DataManager from "../../utils/DataManager";
import arrowImage from '../../image/ic_arrow_right.png'

export default class exchangeDetail extends BasePage {
  config = {
    navigationBarTitleText: '兑换详情'
  }

  defaultProps = {
    detailData:'',
  }

  constructor() {
    super(...arguments)
    this.state = {
      detailData:'',
      addressList: [],
      currentAddId:'',
      currentAddName:'',
      userScore:0,
    }
  }

  onPullDownRefresh(){
    Taro.stopPullDownRefresh();
  }

  componentDidShow(){
    this.loadAddressList();
    this.loadUserScore();
  }

  loadAddressList(){
    let _this = this;
    let url = base_url + 'rest/user/address/addressList'
    Taro.request({
      url:url,
      data: {
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'c',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
      },
      method: 'GET',
      success(res) {
        if (res.data && res.data.data){

          let subList = [];
          for (let i = 0 ; i < res.data.data.length ; i ++){
            let add = res.data.data[i];
            if (i == 0){
              _this.setState({
                currentAddId : add.id,
                currentAddName: add.provinceName + add.cityName + add.areaName + add.address
              })
            }
            let subAdd = {};
            subAdd.address = add.provinceName + add.cityName + add.areaName + add.address;
            subAdd.id = add.id;
            subList.push(subAdd);
          }

          _this.setState({
            addressList: subList,
          })
        }
      },
      fail(){
      }
    })
  }

  loadUserScore(){
    let _this = this;

    let url = base_url + 'rest/user/userDetail'
    Taro.request({
      url:url,
      data: {
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'c',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
      },
      method: 'GET',
      success(res) {
        console.log('userDetail=========' + JSON.stringify(res))
        if (res.data && res.data.data){
          _this.setState({
            userScore : res.data.data.integral
          })
        }
      }
    })
  }

  componentWillMount () {
    this.scoreInfo = this.$router.params.scoreInfo;
    console.log('scoreInfo=========' + this.scoreInfo)
    if (this.scoreInfo){
      let score = JSON.parse(this.scoreInfo);
      this.setState({
        detailData:score
      })
    }
  }

  onCheckLocation = (scoreItem) =>{
    if (!scoreItem){
      return
    }
    const latitude =  scoreItem.latitude
    const longitude =  scoreItem.longitude
    console.log(scoreItem.longitude + ' ' + scoreItem.longitude)
    Taro.openLocation({
      latitude,
      longitude,
      scale: 18
    })
  }

  onChooseAddress = (e) =>{
    const add = this.state.addressList[e.detail.value].address;
    const addId = this.state.addressList[e.detail.value].id;
    this.setState({
      currentAddId:addId,
      currentAddName:add,
    })
  }

  onExchangeClick = () =>{

    if (!this.state.detailData) {
      return
    }
    if (!this.state.currentAddId) {
      Taro.showToast({
        title:'请选择或新增收货地址',
        icon:'none'
      })
      return
    }

    let _this = this;
    Taro.request({
    url:base_url + 'rest/user/receive/receiveGoods',
      data:{
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'wechat',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
        goodsId:this.state.detailData.id,
        addressId: this.state.currentAddId
      },
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      success: (obj) => {
        if (obj.data.status == 'success') {
          Taro.showToast({
            title: '兑换成功',
            icon: 'none',
            duration: 1000
          })
          // let pCount = _this.state.totalCount - 1;
          // _this.setState({
          //   totalCount : pCount
          // })

          Taro.redirectTo({
            url: '/pages/me/myExchange'
          })

        } else {
          Taro.showToast({
            title: obj.data.message,
            icon: 'none',
            duration: 1000
          })
        }
      },
      fail: (obj) => {
        Taro.showToast({
          title: '程序异常',
          icon: 'none',
          duration: 1000
        })
      }
    })
  }

  goToAddAddress = () =>{
    Taro.navigateTo({
      url : `/pages/me/addReceiveAddress`
    })
  }

  render(){

    let score = this.state.detailData;
    let integral = '所需积分：' + score.integral ;
    let allIntegral = integral + '  （剩余积分：' + this.state.userScore + '）';
    let count = '剩余件数：' + score.totalCount;
    let time = '领取时间：' + score.startDate + '--' + score.endDate;


    return(
      <View className='exchange-detail-container'>
        <View className='exchange-detail-info-container'>
          <Image className='exchange-detail-image' src={score.goodsImage} mode='aspectFit'/>
          <View className='exchange-detail-divider'/>
          <View className='exchange-detail-info-sub'>
            <Text className='exchange-detail-text-big'>{score.goodsName}</Text>
            <Text className='exchange-detail-text-score' style='margin-top:10px'>{allIntegral}</Text>
            <Text className='exchange-detail-text-small' style='margin-top:20px'>{count}</Text>
            <Text className='exchange-detail-text-small' style='margin-top:20px'>{time}</Text>
            {score.type == 0 && <View className='score-item-address-container' onClick={this.onCheckLocation.bind(this , score)}>
              <Image style='width:20px;height:20px' src={location_icon}/>
              <Text className='score-item-address'>{score.receiveAddress}</Text>
            </View>}
          </View>
        </View>
        {score.type == 1 && this.state.addressList.length > 0 && <Picker mode='selector' range={this.state.addressList} rangeKey='address' value='0'
                onChange={this.onChooseAddress.bind(this)}>
          <View className='score-post-type-container'>
            <Text className='score-post-type-text'>收货地址</Text>
            <View className='score-post-type-right'>
              <Text className='exchange-detail-address-text'>{this.state.currentAddName}</Text>
              <Image className='score-post-type-arrow' src={arrowImage}/>
            </View>
          </View>
        </Picker>
        }
        {score.type == 1 && this.state.addressList.length <= 0 &&
          <View className='score-post-type-container' onClick={this.goToAddAddress.bind(this)}>
            <Text className='exchange-detail-address-text'>去添加收货地址</Text>
            <Image className='score-post-type-arrow' src={arrowImage}/>
          </View>

        }
        <View className='post-section' onClick={this.onExchangeClick.bind(this)}>
          <Button className='exchange-detail-commit'>确认兑换</Button>
        </View>
      </View>
    )
  }




}





